#!/usr/bin/env node

const https=require('https'),
      http=require('http'),
      log=console.log,
      addr='https://maoyan.com/films?showType=3',
      cheerio=require('cheerio'),
      fs=require('fs'),
      url=require('url');

let opt=(ad)=>{
  let p=url.parse(ad);
  p.headers={
    'Cookie': 'uuid_n_v=v1; uuid=A11BB3C01C2F11EBB8CB3351ABEB4F1B43D9769EB21A40CF97E93BC35C111C73; _lxsdk_cuid=175836b4504ad-0a635b5d2993be-f7b1332-144000-175836b4505c8; _lxsdk=A11BB3C01C2F11EBB8CB3351ABEB4F1B43D9769EB21A40CF97E93BC35C111C73; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; _csrf=daeb6d525c40057973417db6e5903d7369a9d4c0266718b224abfba2ce8ca7d0; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1604227647,1604304277,1604304850,1604643149; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1604643163; __mta=175993117.1604227647100.1604643148906.1604643163203.8; _lxsdk_s=1759c2f544e-8fc-5b9-636%7C%7C4',
    'Host': 'maoyan.com',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-User': '?1',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36',
  };
  return p;
};

function genPage(){
  let html = fs.readFileSync('./index.html');
  return html;

}

get(addr);
function get(ad){
  let movieList=[];
  https.get(opt(ad),(res)=>{
    let data='';

    res.on('data',(chunck)=>{
      data+=chunck;
    });
    res.on('end',()=>{
      var $ =cheerio.load(data);
      $('body').find('.movie-list>dd').each(function(i){
        var movieName=$(this).find('.movie-item-title>a').text();
        var movieId=$(this).find('.movie-item-title>a').attr('data-val').slice(9,-1);
        var movieRange=$(this).find('div.channel-detail-orange').text();

        movieList[i]={'movieId':`${movieId}`,'movieName':`${movieName}`,'movieRange':`${movieRange}`};
      });
      //log(movieList);
    });

  });
  http.createServer((req,res)=>{
    if(req.url === '/'){
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/html');
      res.end(genPage());
                    
    }
    if(req.url==='/getlist'){
      res.end(JSON.stringify(movieList));
    }
  }).listen(8080);

}
